package com.ruoyi.bizsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.bizsys.domain.DeviceContacts;
import com.ruoyi.bizsys.domain.DeviceContactsRelative;
import com.ruoyi.bizsys.domain.DeviceContactsSerialno;
import com.ruoyi.bizsys.mapper.DeviceContactsMapper;
import com.ruoyi.bizsys.mapper.DeviceContactsRelativeMapper;
import com.ruoyi.bizsys.service.IDeviceContactsRelativeService;
import com.ruoyi.bizsys.service.IDeviceContactsSerialnoService;
import com.ruoyi.bizsys.service.IDeviceContactsService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 通讯录授权Service业务层处理
 *
 * @author african-loan
 * @date 2021-10-28
 */
@Slf4j
@Service
public class DeviceContactsServiceImpl extends ServiceImpl<DeviceContactsMapper, DeviceContacts> implements IDeviceContactsService {

    @Autowired
    DeviceContactsMapper deviceContactsMapper;

    @Autowired
    DeviceContactsRelativeMapper deviceContactsRelativeMapper;

    @Autowired
    RedisCache redisCache;

    @Autowired
    ISysConfigService iSysConfigService;

    @Autowired
    IDeviceContactsRelativeService iDeviceContactsRelativeService;

    @Autowired
    IDeviceContactsSerialnoService iDeviceContactsSerialnoService;

    @Override
    public int selectContactsCount(String userId, String applyNo, String tableName) {
        return deviceContactsMapper.selectContactsCount(userId, applyNo, tableName);
    }

    @Override
    public Integer batchSaveContacts(List<DeviceContacts> contactsList, String deviceNo) {
        String tableName = getTableName(deviceNo);
        return batchSaveContactsTableName(contactsList, tableName);
    }

    @Override
    public Integer batchSaveContactsTableName(List<DeviceContacts> contactsList, String tableName) {
        return deviceContactsMapper.batchSaveContacts(contactsList, tableName);
    }

    @Override
    public String getTableName(String deviceId) {
        QueryWrapper<DeviceContactsRelative> deviceContactsQueryWrapper = new QueryWrapper<>();
        deviceContactsQueryWrapper.eq("device_id", deviceId).last("limit 1");
        DeviceContactsRelative one = deviceContactsRelativeMapper.selectOne(deviceContactsQueryWrapper);
        String tableName;
        if (one == null || StringUtils.isBlank(one.getContactsTableName())) {
            //获得最新的表名
            tableName = getNewTableName();
            DeviceContactsRelative deviceContactsRelative = new DeviceContactsRelative();
            deviceContactsRelative.setDeviceId(deviceId);
            deviceContactsRelative.setContactsTableName(tableName);
            iDeviceContactsRelativeService.insertDeviceContactsRelative(deviceContactsRelative);
        } else {
            tableName = one.getContactsTableName();
        }
        return tableName;
    }

    @Override
    public String getNewTableName() {

        String deviceContactsNewTable = redisCache.getCacheObject(Constants.DEVICE_CONTACTS_NEW_TABLE);

        if (StringUtils.isNotBlank(deviceContactsNewTable)) {
            return deviceContactsNewTable;
        } else {
            String newTableName = deviceContactsRelativeMapper.getNewTableName();
            redisCache.setCacheObject(Constants.DEVICE_CONTACTS_NEW_TABLE, newTableName);
            return newTableName;
        }
    }

    public Integer getNewTableNumber() {
        String newTableName = getNewTableName();
        String[] s = newTableName.split("_");
        return Integer.parseInt(s[s.length - 1]);
    }

    @Override
    public void checkNewTableData() {
        Integer cust_contact_split_nums = Integer.parseInt(iSysConfigService.selectConfigByKey("cust_contact_split_nums"));

        Integer newTableNumber = getNewTableNumber();
        Integer count = deviceContactsMapper.getCount(Constants.DEVICE_CONTACTS_TABLE_NAME + newTableNumber);

        if (count >= cust_contact_split_nums) {

            String tableName = Constants.DEVICE_CONTACTS_TABLE_NAME + (newTableNumber + 1);
            deviceContactsMapper.createTable(tableName);
            redisCache.setCacheObject(Constants.DEVICE_CONTACTS_NEW_TABLE, tableName);
        }

    }

    @Override
    public void clearData() {
        log.info("clearData==============进来了");
        //将所有表都取出来
        Integer newTableNumber = getNewTableNumber();

        for (int i = newTableNumber; i >= 1; i--) {

            //拿到所有需要更新的数据
            String tableName = Constants.DEVICE_CONTACTS_TABLE_NAME + i;
            //临时修改长度
            deviceContactsMapper.updateGroupConcatMaxLen();
            List<DeviceContacts> list = deviceContactsMapper.getClearData(tableName);

            //循环所有用户
            for (int j = 0; j < list.size(); j++) {
                DeviceContacts deviceContacts = list.get(j);
                try {
                    clearDataByIds(tableName, deviceContacts.getApplyNo());
                } catch (Exception e) {
                    log.error("清理数据异常，id：{}", deviceContacts.getApplyNo().split(",")[0], e);
                }
            }
        }

    }

    /**
     * 对某个用户的数据进行去重
     *
     * @param tableName
     * @param ids       需要操作的通讯录ids
     */
    @Override
    @Transactional
    public void clearDataByIds(String tableName, String ids) {

        List<String> idList = new ArrayList<>(Arrays.asList(ids.split(",")));

        //没用到的id（重复id）
        List<String> noUseIdList = new ArrayList<>();
        List<String> useList = new ArrayList<>(Arrays.asList(ids.split(",")));

        List<DeviceContacts> list = deviceContactsMapper.getByIds(tableName, idList);
        //合并数据
        Map<DeviceContactsSerialno, String> map = new HashMap<>();
        Map<DeviceContacts, String> map1 = new HashMap<>();

        for (int i = 0; i < list.size(); i++) {

            DeviceContacts deviceContacts = list.get(i);

            DeviceContacts deviceContactsMap = new DeviceContacts();
            deviceContactsMap.setCallName(deviceContacts.getCallName());
            deviceContactsMap.setDeviceId(deviceContacts.getDeviceId());
            deviceContactsMap.setPhone(deviceContacts.getPhone());


            DeviceContactsSerialno deviceContactsSerialno = new DeviceContactsSerialno();
            deviceContactsSerialno.setApplyNo(deviceContacts.getApplyNo());
            deviceContactsSerialno.setDeviceId(deviceContacts.getDeviceId());
            deviceContactsSerialno.setCreateTime(deviceContacts.getCreateTime());


            if (map1.get(deviceContactsMap) != null) {
                noUseIdList.add(list.get(i).getId() + "");
                map.merge(deviceContactsSerialno, map1.get(deviceContactsMap), (oldValue, newValue) -> oldValue + "," + newValue);
            } else {
                map1.put(deviceContactsMap, list.get(i).getId() + "");
                map.merge(deviceContactsSerialno, deviceContacts.getId() + "", (oldValue, newValue) -> oldValue + "," + newValue);
            }
        }

        useList.removeAll(noUseIdList);

        for (DeviceContactsSerialno key : map.keySet()) {
            String value = map.get(key);
            Set set = new HashSet(Arrays.asList(value.split(",")));
            map.put(key, set.toString().trim().replace("[", "").replace("]", ""));
        }
        //插入
        iDeviceContactsSerialnoService.batchSave(map);

        //修改已用到数据
        deviceContactsMapper.updateDeviceId(tableName, useList);
        //删除未用到数据
        if (noUseIdList.size() > 0) {
            deviceContactsMapper.deleteByIds(tableName, noUseIdList);
        }
    }

    @Override
    public int getCntContactsNum(String tableName, String deviceNo, String applyNo) {
        return deviceContactsMapper.getCntContactsNum(tableName, applyNo, deviceNo);
    }

    @Override
    public String get7DaysContactsCount(String tableName, String deviceId) {
        return baseMapper.get7DaysContactsCount(tableName, deviceId);
    }

    @Override
    public void syncExcludePhone() {
        for (int i = getNewTableNumber(); i >= 1; i--) {
            //拿到所有需要更新的数据
            deviceContactsMapper.syncExcludePhone(Constants.DEVICE_CONTACTS_TABLE_NAME + i);
        }
    }

    @Override
    public List<DeviceContacts> getCollectionPhone(List<DeviceContactsRelative> tableName, String userId, int size) {
        return deviceContactsMapper.getCollectionPhone(tableName, userId, size);
    }

}
